#!/usr/bin/env python3
"""
Debug script to diagnose tool generation issues
"""

import sys
import os
import logging
import json

# Add the src directory to Python path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

# Setup detailed logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

def debug_tool_generation():
    """Debug tool generation process"""
    
    try:
        from incloud_mcp_server.config import load_config
        from incloud_mcp_server.swagger.tool_generator import ToolGenerator
        from incloud_mcp_server.swagger.client import SwaggerClient
        
        print("🔧 Loading configuration...")
        
        # Load configuration
        config = load_config('config.yaml')
        
        print(f"✅ Configuration loaded successfully")
        print(f"   Base URL: {config.swagger.base_url}")
        print(f"   Language: {config.language}")
        
        # Get enabled services
        enabled_services = config.get_enabled_services()
        print(f"   Enabled services: {list(enabled_services.keys())}")
        
        # Debug each service
        for service_name, service_config in enabled_services.items():
            print(f"\n🔍 Debugging service: {service_name}")
            print(f"   Service enabled: {service_config.enabled}")
            
            # Get configured APIs
            configured_apis = config.get_service_apis(service_name)
            print(f"   Configured APIs: {len(configured_apis)}")
            
            for i, api in enumerate(configured_apis):
                print(f"     {i+1}. {api.method} {api.path} (enabled: {api.enabled})")
                print(f"        Description: {api.description}")
            
            # Test Swagger client
            print(f"\n   📡 Testing Swagger client for {service_name}...")
            swagger_client = SwaggerClient(config)
            
            try:
                # Get available APIs from Swagger
                available_apis = swagger_client.get_service_apis(service_name)
                print(f"   Available APIs from Swagger: {len(available_apis)}")
                
                for i, api in enumerate(available_apis[:5]):  # Show first 5
                    print(f"     {i+1}. {api.get('method', 'N/A')} {api.get('path', 'N/A')}")
                    print(f"        Summary: {api.get('summary', 'N/A')}")
                
                if len(available_apis) > 5:
                    print(f"     ... and {len(available_apis) - 5} more")
                
            except Exception as e:
                print(f"   ❌ Failed to get Swagger APIs: {e}")
                continue
            
            # Test tool generation
            print(f"\n   🔧 Testing tool generation for {service_name}...")
            tool_generator = ToolGenerator(config)
            
            try:
                tools = tool_generator.generate_service_tools(service_name)
                print(f"   Generated tools: {len(tools)}")
                
                for i, tool in enumerate(tools):
                    print(f"     {i+1}. {tool.__name__}")
                    print(f"        Doc: {tool.__doc__[:100] if tool.__doc__ else 'N/A'}...")
                
            except Exception as e:
                print(f"   ❌ Failed to generate tools: {e}")
                import traceback
                traceback.print_exc()
        
        print("\n✅ Debug completed!")
        
    except Exception as e:
        print(f"\n❌ Debug failed with error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    print("🔍 Debugging Tool Generation Process")
    print("=" * 50)
    
    debug_tool_generation()
    
    print("\n" + "=" * 50)
    print("🎯 Debug completed - check the output above for issues")
